<!-- filename: pages/playlist-detail/playlist-detail.vue (最终正确版) -->
<template>
  <view class="page-container" @click="handlePageClick">
    <Header @open-auth-modal="isAuthModalVisible = true" />
    <AuthModal v-if="isAuthModalVisible" @close="isAuthModalVisible = false" />

    <div class="content-wrapper" style="padding-top: 60px;">
      <view v-if="isLoading" class="loading-state">正在加载歌单...</view>
      <view v-else-if="error" class="error-state">{{ error }}</view>
      
      <view v-else class="playlist-detail-content">
        
        <header class="page-header">
          <div class="header-left">
            <view class="cover-placeholder">
              <image v-if="playlistInfo && playlistInfo.cover_url" :src="playlistInfo.cover_url" class="cover-image" mode="aspectFill" />
              <svg v-else width="40" height="40" viewBox="0 0 24 24" fill="currentColor"><path d="..."/></svg>
            </view>
            <div class="header-info">
          <!-- 【修改】歌单名称，编辑模式下变为输入框 -->
          <input 
            v-if="isEditMode"
            v-model="editablePlaylistName"
            class="playlist-name-input"
          />
          <h1 v-else class="playlist-name">{{ playlistInfo.name }}</h1>

              <span class="song-count">{{ listSummary }}</span>
            </div>
          </div>
          <div class="header-right">
            <div v-if="playlistId != -1" class="action-btn edit-btn" @click="toggleEditMode">
              {{ isEditMode ? '完成' : '编辑' }}
            </div>
            <div class="download-btn" @click="handleDownloadCurrentList">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                <path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z" />
              </svg>
              <span>下载</span>
            </div>
          </div>
        </header>

        <view class="playlist-description">
          <textarea
            v-if="playlistInfo"
            v-model="descriptionText"
            :maxlength="50"
            placeholder="点击添加简介"
            class="description-textarea"
            @blur="handleDescriptionBlur"
          />
          <view class="char-counter">({{ descriptionLength }}/50)</view>
        </view>
        
        <SearchBar 
          v-if="!isEditMode" 
          ref="searchBarRef" 
          @search="handleSearch" 
          @focus="handleSearchBarFocus"
          search-context="local"
          :local-data="allSongsInPlaylist"
        />

        <main class="song-list-container">
          <view v-if="songs.length === 0" class="empty-state">歌单里还没有歌曲哦</view>
          
          <view 
            v-else 
            class="song-list-wrapper"
            @dragover.prevent="handleDragOver"
            @drop.prevent="handleDrop"
            @dragleave="handleDragLeave"
          >
            <div class="drop-placeholder" :class="{ 'active': isEditMode && dropIndex === 0 && dropPosition === 'top' }"></div>

            <view 
              v-for="(song, index) in songs"
              :key="song.id"
              class="song-item-wrapper" 
              :class="{ 'is-editing': isEditMode }"
            >
              <div v-if="isEditMode" class="remove-btn" @click.stop="handleRemoveSong(song.id, index)">
                 <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11H7v-2h10v2z"/></svg>
              </div>
              
              <div v-if="isEditMode" class="drag-handle" 
                :draggable="true"
                @dragstart="handleDragStart(index, $event)"
                @dragend="handleDragEnd"
                @dragenter.prevent="handleDragEnter(index, $event)"
              >
                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor"><path d="M3 15h18v-2H3v2zm0 4h18v-2H3v2zm0-8h18V9H3v2zm0-6v2h18V5H3z"/></svg>
              </div>

              <div class="song-card-container" :class="{ 'dragging-source': dragIndex === index }">
                <SongCard
                  :song="song"
                  :is-edit-mode="isEditMode"
                  :ref="(el) => setSongCardRef(song.id, el)"
                  @play="handlePlaySong"
                  @filter="handleSongCardFilter"
                  @menuToggled="handleMenuToggled"
                />
              </div>

              <div class="drop-placeholder" :class="{ 'active': isEditMode && dropIndex === index && dropPosition === 'bottom' }"></div>
            </view>
          </view>
        </main>
      </view>
    </div>

    <Player v-if="playerStore.showPlayer" />
  </view>
</template>



<script setup>
import { computed, ref, onBeforeUpdate } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { useAuthStore } from '@/store/auth';
import { usePlayerStore } from '@/store/player';
import { request } from "@/utils/request"; // 【核心修改1】
import { downloadSongs } from "@/utils/download.js";

import Header from '@/components/Header/Header.vue';
import AuthModal from '@/components/AuthModal/AuthModal.vue';
import Player from '@/components/Player.vue';
import SongCard from '@/components/SongCard/SongCard.vue';
import SearchBar from '@/components/SearchBar/SearchBar.vue';

const authStore = useAuthStore();
const playerStore = usePlayerStore();
const isAuthModalVisible = ref(false);

const playlistInfo = ref(null);
const songs = ref([]);
const allSongsInPlaylist = ref([]);
const isLoading = ref(true);
const error = ref('');
let playlistId = null;

const searchBarRef = ref(null);
const songCardRefs = ref({});
const openedMenuCardId = ref(null);

const isEditMode = ref(false);
const editablePlaylistName = ref('')
const dragIndex = ref(null);
const dropIndex = ref(null);
const dropPosition = ref(null);
let scrollInterval = null;

const descriptionText = ref('');
const descriptionLength = computed(() => (descriptionText.value || '').length);

const listSummary = computed(() => `共 ${allSongsInPlaylist.value.length} 首歌`);

// --- 【核心修改2】重写所有 API 请求函数 ---

const fetchPlaylistDetails = async () => {
  isLoading.value = true;
  error.value = '';
  const params = new URLSearchParams({ page: 1, limit: 1000, sort_by: 'sort_order' });
  try {
    const data = await request({
      url: `/api/playlists/${playlistId}?${params.toString()}`,
      method: 'GET'
    });
    playlistInfo.value = data.info;
    descriptionText.value = data.info.description || '';
    allSongsInPlaylist.value = [...data.songs];
    songs.value = [...data.songs];
  } catch (err) {
    error.value = err?.data?.error || '加载歌单失败';
  } finally {
    isLoading.value = false;
  }
};

const handleDescriptionBlur = async () => {
  if (!playlistInfo.value || (playlistInfo.value.description || '') === descriptionText.value) { return; }
  const oldDescription = playlistInfo.value.description;
  playlistInfo.value.description = descriptionText.value;
  try {
    await request({
      url: `/api/playlists/${playlistId}/description`,
      method: 'PUT',
      data: { description: descriptionText.value },
    });
    uni.showToast({ title: '简介已保存', icon: 'none' });
  } catch (error) {
    playlistInfo.value.description = oldDescription;
    uni.showToast({ title: '简介更新失败', icon: 'error' });
  }
};

const saveOrder = async () => {
  const song_ids = songs.value.map(s => s.id);
  uni.showLoading({ title: '保存中...' });
  try {
    await request({
      url: `/api/playlists/${playlistId}/songs/order`,
      method: 'PUT',
      data: { song_ids },
    });
    uni.showToast({ title: '已保存', icon: 'success' });
    allSongsInPlaylist.value = [...songs.value];
  } catch (error) {
    uni.showToast({ title: '保存失败', icon: 'error' });
  } finally {
    uni.hideLoading();
  }
};

const handleNameUpdate = async () => {
  const newName = editablePlaylistName.value.trim();
  if (!newName || newName === playlistInfo.value.name) {
    return;
  }
  
  const oldName = playlistInfo.value.name;
  playlistInfo.value.name = newName;

  try {
    await request({
      url: `/api/playlists/${playlistId}/name`,
      method: 'PUT',
      data: { name: newName },
    });
    // 名称更新成功后，可以考虑是否需要刷新页面或 store
  } catch (error) {
    playlistInfo.value.name = oldName;
    uni.showToast({ title: '名称更新失败', icon: 'error' });
  }
};

// --- 无需修改的函数 ---
onLoad((options) => {
  playlistId = options.id;
  const playlistName = decodeURIComponent(options.name);
  if (!playlistId) {
    error.value = '无效的歌单ID'; isLoading.value = false; return;
  }
  if (playlistName) {
    uni.setNavigationBarTitle({ title: playlistName });
  }
  if (!authStore.isLoggedIn) {
    error.value = '请先登录'; isLoading.value = false;
    setTimeout(() => { isAuthModalVisible.value = true; }, 500);
    return;
  }
  fetchPlaylistDetails();
});

const handleSearch = (payload) => {
  const keywords = payload.value.trim().toLowerCase().split(' ').filter(Boolean);
  if (keywords.length === 0) {
    songs.value = [...allSongsInPlaylist.value];
    return;
  }
  songs.value = allSongsInPlaylist.value.filter(song => {
    const songText = [ song.title, song.cover_artists, song.original_artists, song.language_name, song.status_name, song.cover_date.replace(/-/g, '') ].join(' ').toLowerCase();
    return keywords.every(kw => songText.includes(kw));
  });
};

const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value;
  if (isEditMode.value) {
    editablePlaylistName.value = playlistInfo.value.name;
    if (searchBarRef.value) {
      searchBarRef.value.setSearchTextAndExecute('');
    }
    songs.value = [...allSongsInPlaylist.value];
    if (openedMenuCardId.value) {
      const card = songCardRefs.value[openedMenuCardId.value];
      if (card) card.closeMenu();
    }
  } else {
    handleNameUpdate();
    saveOrder();
  }
};

const handleDragStart = (index, event) => { dragIndex.value = index; };
const handleDragEnter = (index, event) => {
  if (index === dragIndex.value) { dropPosition.value = null; return; };
  const rect = event.currentTarget.getBoundingClientRect();
  const midpoint = rect.top + rect.height / 2;
  dropPosition.value = event.clientY < midpoint ? 'top' : 'bottom';
  dropIndex.value = index;
};
const handleDragOver = (event) => {
  if (dragIndex.value === null) return;
  const viewportHeight = window.innerHeight;
  const header = document.querySelector('.header-container');
  const headerHeight = header ? header.offsetHeight : 60;
  const player = document.querySelector('.mini-player-container');
  const playerHeight = player ? player.offsetHeight : 0;
  const scrollZone = 100;
  if (event.clientY > headerHeight && event.clientY < headerHeight + scrollZone) {
    startScrolling(-20);
  } else if (event.clientY < viewportHeight - playerHeight && event.clientY > viewportHeight - playerHeight - scrollZone) {
    startScrolling(20);
  } else {
    stopScrolling();
  }
};
const handleDragLeave = (event) => {
  const listWrapper = event.currentTarget;
  const rect = listWrapper.getBoundingClientRect();
  if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) {
    dropIndex.value = null;
    dropPosition.value = null;
  }
};
const handleDrop = () => {
  stopScrolling();
  if (dragIndex.value !== null && dropIndex.value !== null) {
    const itemToMove = songs.value.splice(dragIndex.value, 1)[0];
    let targetIndex = dropIndex.value;
    if (dragIndex.value < dropIndex.value) { targetIndex--; }
    if (dropPosition.value === 'bottom') {
      songs.value.splice(targetIndex + 1, 0, itemToMove);
    } else {
      songs.value.splice(targetIndex, 0, itemToMove);
    }
  }
  handleDragEnd();
};
const handleDragEnd = () => { stopScrolling(); dragIndex.value = null; dropIndex.value = null; dropPosition.value = null; };
const startScrolling = (speed) => { if (scrollInterval) return; scrollInterval = setInterval(() => { window.scrollBy(0, speed); }, 15); };
const stopScrolling = () => { clearInterval(scrollInterval); scrollInterval = null; };

const handleRemoveSong = (songId, index) => { songs.value.splice(index, 1); };
const handleDownloadCurrentList = () => { downloadSongs(songs.value.map(s => s.id)); };
const handlePlaySong = (songId) => { if (isEditMode.value) return; playerStore.setPlaylistAndPlay(songs.value, songId); };
onBeforeUpdate(() => { songCardRefs.value = {}; });
const setSongCardRef = (id, el) => { if (el) { songCardRefs.value[id] = el; } };
const handleSongCardFilter = (searchTerm) => { if (searchBarRef.value) { searchBarRef.value.setSearchTextAndExecute(searchTerm); } };
const handleMenuToggled = (payload) => {
  if(isEditMode.value) return;
  const { id, isOpen } = payload;
  if (isOpen) {
    if (openedMenuCardId.value && openedMenuCardId.value !== id) {
      const oldCard = songCardRefs.value[openedMenuCardId.value];
      if (oldCard) oldCard.closeMenu();
    }
    openedMenuCardId.value = id;
  } else if (openedMenuCardId.value === id) {
    openedMenuCardId.value = null;
  }
};
const handlePageClick = () => {
  if (searchBarRef.value) { searchBarRef.value.closeSearchResults(); }
  if (openedMenuCardId.value) {
    const card = songCardRefs.value[openedMenuCardId.value];
    if (card) card.closeMenu();
  }
  handleDragEnd();
};
const handleSearchBarFocus = () => {
  if (openedMenuCardId.value) {
    const card = songCardRefs.value[openedMenuCardId.value];
    if (card) card.closeMenu();
  }
};
</script>

<style scoped lang="scss">
/* --- 页面基础布局 --- */
.page-container {
  display: flex;
  justify-content: center;
  width: 100%;
  min-height: 100vh;
  background-color: #f8f8f8;
}
.content-wrapper {
  width: 100%;
  max-width: 800px;
  background-color: #ffffff;
}
.loading-state, .error-state, .empty-state {
  text-align: center;
  padding: 80px 20px;
  color: #888;
}

.playlist-detail-content { 
  padding-bottom: 150px; 
}

/* --- 头部样式 --- */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  gap: 20px;
  border-bottom: 1px solid #f0f0f0;
}
.header-left {
  display: flex; align-items: center; gap: 15px; min-width: 0;
}
.header-info {
  display: flex; flex-direction: column; min-width: 0;
}
.cover-placeholder {
  width: 60px; height: 60px; flex-shrink: 0; border-radius: 8px;
  display: flex; align-items: center; justify-content: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  color: #8fa6c7;
  overflow: hidden;
}
.cover-image {
  width: 100%;
  height: 100%;
}
.playlist-name {
  font-size: 22px; font-weight: bold; color: #333;
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
/* 【新增】名称输入框样式 */
.playlist-name-input {
  font-size: 22px;     /* 缩小字体 */
  font-weight: normal; /* 取消加粗 */
  color: #333;
  border: 1px solid #007aff;
  border-radius: 6px;
  padding: 5px 10px;
  width: 100%;
  box-sizing: border-box;
}
.song-count {
  font-size: 14px; color: #888; margin-top: 5px;
}
.header-right {
  display: flex; align-items: center; gap: 15px; flex-shrink: 0;
}
.action-btn {
  padding: 8px 16px; border-radius: 8px; font-size: 14px; font-weight: 500;
  cursor: pointer; transition: background-color 0.2s;
}
.edit-btn {
  background-color: #007aff; color: white;
  &:hover { background-color: #0056b3; }
}
.download-btn {
  display: flex; align-items: center; padding: 8px 12px;
  background-color: #f0f0f0; border-radius: 8px; cursor: pointer;
  transition: background-color 0.2s;
  &:hover { background-color: #e0e0e0; }
  span { margin-left: 8px; font-size: 14px; font-weight: 500; }
}

/* --- 简介样式 --- */
.playlist-description {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 15px 20px;
}
.description-textarea {
  flex-grow: 1; padding: 8px 12px; box-sizing: border-box;
  border: 1px solid #f0f0f0; border-radius: 6px; font-size: 14px;
  color: #666; background-color: #f9f9f9; height: 40px;
  line-height: 1.5; transition: border-color 0.2s, background-color 0.2s;
  &:focus { border-color: #007aff; background-color: #fff; }
}
.char-counter {
  flex-shrink: 0; font-size: 12px; color: #aaa;
}

/* --- 【最终修正】布局与拖拽样式 --- */

/* 歌曲列表的 padding 由 song-item-wrapper 提供 */
.song-list-wrapper {
  padding-top: 10px;
}

.song-item-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  padding: 0 20px; /* 恢复左右边距 */
}

.song-card-container {
  flex-grow: 1;
  min-width: 0;
}

.remove-btn, .drag-handle {
  display: none;
}

/* 仅在编辑模式下 */
.is-editing {
  background-color: #fafafa;
  border-top: 1px dashed #cccccc;
  border-bottom: 1px dashed #cccccc;
  margin-top: -1px;
  padding: 0; /* 编辑时移除 wrapper 的 padding */

  .remove-btn {
    display: flex; align-items: center; justify-content: center;
    width: 40px; cursor: pointer; color: #e5245e;
  }
  .drag-handle {
    display: flex; align-items: center; justify-content: center;
    width: 40px; cursor: grab; color: #888;
  }
  .drag-handle:active {
    cursor: grabbing;
  }
  
  .song-card-container > :deep(.song-card) {
    border-bottom: none;
    padding: 10px 0;
  }
}

.dragging-source {
  opacity: 0.4;
}

.drop-placeholder {
  height: 0;
  overflow: hidden;
  position: relative;
  transition: height 0.1s ease;
  &::before {
    content: ''; position: absolute; left: 20px; right: 20px;
    top: 50%; transform: translateY(-50%); height: 4px;
    background-color: #007aff; border-radius: 2px;
  }
}
.drop-placeholder.active {
  height: 15px;
}
</style>